package cn.com.swu.mianyangapp.ui.news;

import android.annotation.SuppressLint;
import android.nfc.Tag;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.sql.Timestamp;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

import cn.com.swu.mianyangapp.R;
import cn.com.swu.mianyangapp.ui.bean.News;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link NewsListFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class NewsListFragment extends Fragment {

    final private String mIp = "192.168.58.15:8081";
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    public Handler mHandler;
    private String mParam1;
    private String mParam2;
    private List<News> mNews;
    private NewsListAdapter mNewsListAdapter;
    private RecyclerView mRecyclerView;

    public NewsListFragment() {
        // Required empty public constructor
    }

    public static NewsListFragment newInstance(String param1, String param2) {
        NewsListFragment fragment = new NewsListFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_news_list, container, false);
    }

    @SuppressLint("HandlerLeak")
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {

        super.onViewCreated(view, savedInstanceState);

        initDate();
        mHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        mNews = new ArrayList<>();
                        mNews.addAll((List<News>)msg.obj);
                        String Tag = "OKHttp";
                        Log.e(Tag,mNews.toString());
                        Log.e(Tag,msg.obj.toString());
                        mNewsListAdapter = new NewsListAdapter(getContext(),mNews);
                        mRecyclerView = view.findViewById(R.id.news_show_recycler);
                        mRecyclerView.getRecycledViewPool();
                        mRecyclerView.getRecycledViewPool().setMaxRecycledViews(0, 10);
                        mRecyclerView.setAdapter(mNewsListAdapter);
                        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
                        mRecyclerView.setLayoutManager(layoutManager);
                        break;
                }

            }
        };


    }

    private void initDate() {
        OkHttpClient client = new OkHttpClient();
        FormBody body = new FormBody.Builder().build();
        Request request = new Request.Builder()
                .url("http://"+ mIp + "/select_news/2/"+mParam1)
                .addHeader("Accept-Language","zh-CN,zh;q=0.9")
                .post(body)
                .build();

        Call call = client.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String Tag = "OKHttp";
                Log.e(Tag,e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                JSONArray jsonArray = JSON.parseArray(result);
                List<News> list = JSONObject.parseArray(jsonArray.toJSONString(), News.class);
                Message msg = Message.obtain();
                msg.what = 1; // 消息标识
                msg.obj = list; // 消息内存存放
                mHandler.sendMessage(msg);
            }
        });

//        String[] title = {"测试1","测试2","测试3"};
//        String[] author = {"lk","sjh","xf"};
//        for(int i = 0; i<title.length;i++){
//            News news1 = new News();
//            news1.setNews_name(title[i]);
//            news1.setNews_author(author[i]);
//            mNews.add(news1);
//        }

    }

}

